package com.doucat.support.component.permission;

import android.content.pm.PackageManager;
import android.util.Log;

/**
 * -----------------------------------------------------------------
 * Copyright (C) 2021-2031, by tonly, All rights reserved.
 * -----------------------------------------------------------------
 * File: BasePermission.java
 * Author: wangfy
 * Create: 2021/7/28 9:23
 */
public abstract class BasePermission implements PermissionRequester {
    protected String TAG=getClass().getSimpleName();

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        if (requestCode == PermissionProxy.REQUEST_CODE_PERMISSION) {
            if (verifyPermissions(grantResults)) {
                permissionSuccess(requestCode);
            } else {
                permissionFail(requestCode);
            }
        }
    }

    private PermissionListener permissionListener;
    @Override
    public void setPermissionListener(PermissionListener permissionListener) {
        this.permissionListener=permissionListener;
    }

    /**
     * 获取权限成功
     *
     * @param requestCode
     */
    private void permissionSuccess(int requestCode) {
        Log.d(TAG, "获取权限成功=" + requestCode);
        if(permissionListener!=null){
            permissionListener.permissionSuccess(requestCode);
        }
    }

    /**
     * 权限获取失败
     * @param requestCode
     */
    private void permissionFail(int requestCode) {
        Log.d(TAG, "获取权限失败=" + requestCode);
        if(permissionListener!=null){
            permissionListener.permissionFail(requestCode);
        }
    }

    /**
     * 确认所有的权限是否都已授权
     *
     * @param grantResults
     * @return
     */
    public boolean verifyPermissions(int[] grantResults) {
        if(grantResults.length==0){
            return false;
        }
        for (int grantResult : grantResults) {
            if (grantResult != PackageManager.PERMISSION_GRANTED) {
                return false;
            }
        }
        return true;
    }
}